package com.lenovo.leos.filebrowser.netdisk;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity.OnTitleIconClickListener;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.engine.util.FileUtil;
import com.lenovo.leos.filebrowser.engine.util.HzToPy;
import com.lenovo.leos.filebrowser.engine.util.MimeTypeParser;
import com.lenovo.leos.filebrowser.engine.util.MimeTypes;
import com.lenovo.leos.filebrowser.netdisk.LenovoAdapter.ViewHolder;
import com.lenovo.leos.filebrowser.netdisk.NetDiskManager.OnNotifyListener;
import com.lenovo.leos.filebrowser.ui.BaseActivity;
import com.lenovo.leos.filebrowser.ui.Constant;
import com.lenovo.leos.filebrowser.ui.TdActivity;

public class LenovoActivity extends BaseActivity implements
		OnTitleIconClickListener, OnClickListener, OnTouchListener {

	private static final String TAG = "LenovoActivity";

	private class Position {
		private static final String TAG = "Postion";

		private NetFile mfDir = null;
		private int miIndex = 0;

		public Position(int index, NetFile file) {
			if (0 > index || null == file || !file.isDirectory()) {
				if (TAG_FLAG)
					Log.e(TAG, "invalid parameter in Position");
				return;
			}
			miIndex = index;
			mfDir = file;
		}

		public void setIndex(int index) {
			if (0 > index) {
				if (TAG_FLAG)
					Log.e(TAG, "invalid index in setIndex");
				return;
			} else
				miIndex = index;
		}

		public int getIndex() {
			return miIndex;
		}

		public void setDir(NetFile file) {
			if (null == file || !file.isDirectory()) {
				if (TAG_FLAG)
					Log.e(TAG, "invalid parameter in setPosY");
				return;
			} else
				mfDir = file;
		}

		public NetFile getDir() {
			return mfDir;
		}

		public void dump() {
			if (TAG_FLAG) {
				Log.d(TAG, "===== Position Object Content =====");
				Log.d(TAG, "the index is: " + String.valueOf(miIndex));
				Log.d(TAG, "the dir is: " + mfDir.getAbsolutePath());
				Log.d(TAG, "===================================");
			}
		}
	};

	private static final String ZIP_MIMETYPE = "compressor/zip";// add xieqm
																// 110112

	private enum DISPLAYMODE {
		ABSOLUTE, RELATIVE
	};

	public final static int _LIST = 10;
	public final static int _SELECT = 11;

	protected final int SUB_ACTIVITY_REQUEST_CODE = 1337;
	// private final String root = Constant.root;
	private final String root = "/";
	// private final String localroot = Constant.localroot;
	private final String sdroot = "/";
	// private LOCATION location = LOCATION.LOCAL;
	public static boolean isUDiskMnt = false;

	private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;

	/** Contains directories and files together */
	private List<NetFileItem> directoryEntries = new ArrayList<NetFileItem>();
	/** Dir separate for sorting */
	List<NetFileItem> mListDir = new ArrayList<NetFileItem>();
	/** Files separate for sorting */
	List<NetFileItem> mListFile = new ArrayList<NetFileItem>();
	/** SysDir separate for sorting */
	List<NetFileItem> mListSys = new ArrayList<NetFileItem>();

	private NetFile currentDirectory = NetDiskConstant.NET_DISK_ROOT;

	// a list contains all selected file objects;
	public static List<NetFile> MarkedFile = new ArrayList<NetFile>();
	// flag to identify whether some files are selected.
	// The activities of operation menu items(delete,cut,copy,compress) are
	// depends on isSelected
	public static boolean isSelected = false;
	// flag to identify cut or copy operation.
	// The activities of operation menu item(paste) are depends on cut_copy
	public static boolean delete = false;
	public static boolean download = false;

	private static LinkedList<Position> sllPos = new LinkedList<Position>();

	public enum OPTYPE {
		CUT, COPY
	};

	public static OPTYPE opType;
	// the state of the progress in.
	public static int State;

	// define menu options ID
	private static final int PRE_DOWNLOAD = Menu.FIRST;
	private static final int NEW_ID = Menu.FIRST + 1;
	private static final int DEL_ID = Menu.FIRST + 2;
	private static final int TASK_MANAGER = Menu.FIRST + 3;
	private static final int RENAME_ID = Menu.FIRST + 4;
	private static final int SWITCHING_DIRECTORY = Menu.FIRST + 5;
	private static final int DELETE = Menu.FIRST + 6;
	private static final int PRE_UPLOAD = Menu.FIRST + 7;
	private static final int DOWNLOAD = Menu.FIRST + 8;

	LenovoAdapter itemList;
	public static Button btnSelectAll;// modified by PH 091024
	public static Button btnCancleAll;// modified by PH 091024
	private TextView tv = null;
	// add by PH 091011
	private static MimeTypes mMimeTypes = null;
	// end PH 091011
	// add by PH 091012
	public static final String ACTION_PICK_DIRECTORY = "org.openintents.action.PICK_DIRECTORY";
	// end PH 091012
	// add by PH 091013
	public static int officeFlag;
	String mInitDefaultPath;
	// end PH 091013
	boolean openfile = false;

	private static boolean nothing = false;
	// add by PH 091024
	private static final int FILE_NAME_NUM_MAX = 85;

	boolean mToCloseSend = false;
	File searchFile;
	boolean search = false;
	boolean searchDecom = false;
	String searchpath;
	String searchpathnofile;
	InputMethodManager inputMethodManager;
	private boolean sdRemoved = false;
	private ProgressDialog mProgressDialog;
	private MyBrowseToThread mBrowseToThread = null;
	private MyBrowseToThread mOperatorThread = null;
	MyBrowserToHandler mEH = null;
	private static final int SPACE_MSG = 50000;
	private static final int BROWSETO_RESULT_MSG = 40000;
	private static final int DELETE_FILE_MSG = 30000;
	private static final int CREATE_DIR_MSG = 20000;
	private static final int RENAME_MSG = 10000;
	boolean browsetoThreadFlag = false;
	boolean SdcardUnmounted = false;
	TextView t;
	boolean init = false;
	boolean mBrowseToThreadStop = false;
	String arrfilename;
	String arrsubdir;
	String arrfilenum;
	String arrtotalfileSize;
	String arrmodifyDate;
	TextView mSubFile;
	TextView mTotalSize;
	TextView mSubDir;
	ListView mlvContent;

	private Position mpstCur = null;

	private static final boolean TAG_FLAG = true;
	public final static int RESULT_LIST = 12;
	private static LenovoActivity instance = new LenovoActivity();
	private static String projectState;
	private static String menuFlags;
	public static TextView downloadBtn;
	private static final String OPEN_SAVE = "android.intent.action.OPEN_SAVE_DIALOG";
	private static final int LENOVO_MODE_SAVE_FILE = 3;
	private AlertDialog dialog, renameDialog;
	private TextView sdcardText;
	private static final int MODE_SELECT_PATH = 1;
	private boolean mReceiver = false;
	private String sdCardtatus = Environment.getExternalStorageState();
	private LinearLayout layout, phoneLayout, sdcardLayout, lenovoLayout;
	private static String mUpload, mDownload;
	public static boolean downFlag = false; // download finish is true
	private TextView sumSpace, remainingSpace;
	private String sSpace, sRemainingSpace;
	private boolean delFlag; // delete success is true
	private NetFile mNetFile, renameNetFile;
	private int count; // delete count
	private boolean newDirFlag; // refresh when create a new dir
	private String newName; //
	String[] netFileIds; // download ids
	String[] netFileNames; // download names
	private static boolean[] netFileTypes; // download type, dir is true
	private static String uploadFileId; // upload lenovo dir id

	private NetDiskManager mndManager = null;

	List<NetFile> mlndItems = null;

	long mlCurOp = -1;

	public static LenovoActivity getInstance() {
		return instance;
	}

	private OnNotifyListener mntListener = new OnNotifyListener() {

		public void onOpNotify(Long opId, Bundle data) {
			Log.i(TAG, "==> onOpNotify");

			if (opId == mlCurOp) {
				ProgressMessageDialog.cancelDialog();

				mndManager.unbindOpService();
			}
		}

		public void onServiceNotify(int msgId, String content) {
			Log.i(TAG, "==> onServiceNotify");

			Log.i(TAG, "the message is " + msgId);
		}

	};

	private class MyBrowserToHandler extends Handler {
		public MyBrowserToHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			Log.i(TAG, "==> handleMessage");

			if (msg.what == BROWSETO_RESULT_MSG) {
				itemList.setListItems(directoryEntries);
				mlvContent.setAdapter(itemList);
				if (directoryEntries.size() == 0) {
					nothing = true;
					t.setText(R.string.not_found);
					t.setVisibility(View.VISIBLE);
					mlvContent.setVisibility(View.GONE);
				} else {
					mlvContent.setVisibility(View.VISIBLE);
					nothing = false;
					t.setVisibility(View.GONE);

					if (null != mpstCur) {
						NetFile dir = mpstCur.getDir();
						if (dir.equals(currentDirectory)) {
							mlvContent.setSelection(mpstCur.getIndex());
						} else {
							mlvContent.setSelection(0);
						}
					} else {
						mlvContent.setSelection(0);
					}
				}
				browsetoThreadFlag = false;
				getSpace();
			} else if (msg.what == DELETE_FILE_MSG) {
				if (TAG_FLAG) {
					Log.d(TAG,
							"the MarkedFile is  =========" + MarkedFile.size());
					Log.d(TAG, "the count is  =========" + count);
				}
				if (MarkedFile.size() == count) {
					sortedFileList(mlndItems);
					itemList.setListItems(directoryEntries);
					itemList.notifyDataSetChanged();
					mlvContent.setAdapter(itemList);
				}
				delFlag = false;
				isSelected = false;
				getSpace();
			} else if (msg.what == CREATE_DIR_MSG) {
				sortedFileList(mlndItems);
				itemList.setListItems(directoryEntries);
				itemList.notifyDataSetChanged();
				mlvContent.setAdapter(itemList);
				getSpace();
			} else if (msg.what == RENAME_MSG) {
				sortedFileList(mlndItems);
				itemList.setListItems(directoryEntries);
				itemList.notifyDataSetChanged();
				mlvContent.setAdapter(itemList);
				ProgressMessageDialog.cancelDialog();
			} else if (msg.what == SPACE_MSG) {
				if (TAG_FLAG) {
					Log.d(TAG, "the sSpace is  =========" + sSpace);
					Log.d(TAG, "the remainingSpace is  ========="
							+ remainingSpace);
				}
				if (sSpace != null && sRemainingSpace != null) {
					ProgressMessageDialog.cancelDialog();
					sumSpace.setText(getString(R.string.total_size) + sSpace);
					remainingSpace.setText(getString(R.string.surplus_space)
							+ sRemainingSpace);
				}
			}
		}
	}

	private void getSpace() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> getSpace");
		}
		mOperatorThread = new MyBrowseToThread(LenovoActivity.this) {
			public void run() {

				long id = mndManager.getSpace();
				if (TAG_FLAG) {
					Log.i(TAG, "the id is ----------" + id);
				}

				NetDiskOpResult item = mndManager.getResult(id);
				try {
					while (item == null) {
						item = mndManager.getResult(id);
						try {
							Thread.sleep(100);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
					}
					sRemainingSpace = item.getFreespace();
					sSpace = item.getTotalspace();
					if (TAG_FLAG) {
						Log.d(TAG, "the getSpace sSpace is  ---------------"
								+ sSpace);
						Log.d(TAG,
								"the getSpace remainingSpace is  ----------------"
										+ remainingSpace);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
				mOperatorThread.onGetSpace();
			}
		};
		mOperatorThread.start();

	}

	private void initData() {
		if (null == sllPos) {
			sllPos = new LinkedList<Position>();
		} else
			sllPos.clear();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		Log.e(TAG, "==> onCreate");

		super.onCreate(icicle);

		mndManager = NetDiskManager.getInstance(this);
		mndManager.bindOpService();
		// mndManager.setEnableNotify(true);
		// mndManager.setOnOpNotifyListener(mntListener);

		projectState = getIntent().getStringExtra("projectState");
		initData();
		MarkedFile.clear();
		if (TAG_FLAG) {
			Log.d(TAG, "the directoryEntries is -------------------"
					+ directoryEntries.size());
		}
		itemList = new LenovoAdapter(this, this.directoryEntries);
		mEH = new MyBrowserToHandler(Looper.myLooper());
		this.customTitleIcon(0, 0, 0, this);
		delete = false;
		download = false;
		initMimeTypes();
		State = _LIST;
		initState();
		Intent myintent = getIntent();
		mInitDefaultPath = myintent.getStringExtra("INIT_DEFAULT_PATH");
		browseToRoot();
		mlvContent.setSelection(0);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (TAG_FLAG)
			Log.e(TAG, "==> onResume");
		if (mndManager == null) {
			mndManager = NetDiskManager.getInstance(this);
			mndManager.bindOpService();
		}
		State = _LIST;
		initState();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (browsetoThreadFlag) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
		}
		if (mReceiver) {
			unregisterReceiver(sdCardIntentReceiver);
			if (TAG_FLAG)
				Log.i(TAG, "*********OnDestroy unregisterReceiver *********");
		}
		if (null != dialog) {
			dialog.cancel();
		}
		if (null != renameDialog) {
			renameDialog.cancel();
		}

		if (null != mndManager) {
			mndManager.unbindOpService();
			mndManager = null;
		}

	}

	private void initState() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> initState");
		}
		getWindow()
				.addFlags(WindowManager.LayoutParams.FLAG_ROCKET_MENU_NOTIFY);
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		switch (State) {
		case _LIST:
			setContentView(R.layout.lenovo_main);
			setTitle(R.string.lenovo);
			sumSpace = (TextView) findViewById(R.id.sumSpace);
			remainingSpace = (TextView) findViewById(R.id.remainingSpace);
			t = (TextView) findViewById(R.id.empty);
			tv = (TextView) findViewById(R.id.tv);

			if (TAG_FLAG) {
				Log.d(TAG, "the currentDirectory is ============="
						+ currentDirectory);
			}
			setLocationText(currentDirectory.getAbsolutePath());
			if (sSpace != null && sRemainingSpace != null) {
				sumSpace.setText(getString(R.string.total_size) + sSpace);
				remainingSpace.setText(getString(R.string.surplus_space)
						+ sRemainingSpace);
			}
			mlvContent = (ListView) findViewById(android.R.id.list);
			itemList.notifyDataSetChanged();
			mlvContent.setAdapter(itemList);
			break;
		case _SELECT:
			if (!MarkedFile.isEmpty()) {
				MarkedFile.clear();
				isSelected = false;
			}
			if (menuFlags.equals(DEL_ID + "")) {
				deleteSelect();
			} else if (menuFlags.equals(PRE_DOWNLOAD + "")) {
				downloadSelect();
			}
			break;

		}
		mlvContent.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				if (TAG_FLAG)
					Log.d(TAG, "==>setOnItemClickListener ");
				if (State == _LIST) {
					NetFile clickedFile = null;
					switch (LenovoActivity.this.displayMode) {
					case RELATIVE:
					case ABSOLUTE:
						NetFileItem item = (NetFileItem) arg0.getAdapter()
								.getItem(position);
						if (null != item) {
							NetFile nf = item.getFile();
							Log.i(TAG,
									"the clicked file is "
											+ nf.getAbsolutePath());
							clickedFile = nf;
						}
						uploadFileId = clickedFile.getID();
						if (TAG_FLAG) {
							Log.d(TAG, "the uploadFileId is =============== "
									+ uploadFileId);
						}
						break;
					}

					if (clickedFile != null) {
						if (TAG_FLAG) {
							Log.d(TAG, "the clickedFile is -----------------"
									+ clickedFile.isDirectory());
						}
						netFileIds = null;
						netFileNames = null;
						netFileIds = new String[1];
						netFileNames = new String[1];
						netFileTypes = new boolean[1];
						netFileIds[0] = clickedFile.getID();
						netFileNames[0] = clickedFile.getName();
						netFileTypes[0] = clickedFile.isDirectory();

						if (TAG_FLAG) {
							Log.d(TAG, "the netFileIds is ********"
									+ netFileIds[0]);
							Log.d(TAG, "the netFileNames is ***********"
									+ netFileNames[0]);
							Log.d(TAG, "the netFileTypes is ***********"
									+ netFileTypes[0]);
						}
						if (clickedFile.isDirectory()) {
							if (State == _SELECT) {
								LenovoActivity.MarkedFile.clear();
								isSelected = false;
							}
						} else {
							if (TAG_FLAG) {
								Log.d(TAG, "the clickedFile is file");
							}
							new AlertDialog.Builder(LenovoActivity.this)
									.setMessage(R.string.isDown)
									.setPositiveButton(
											R.string.alert_dialog_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													downLoad(projectState,
															netFileIds,
															netFileNames,
															netFileTypes);
												}
											})
									.setNegativeButton(
											R.string.alert_dialog_cancel,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
												}

											}).show();
						}
					}
					// currentDirectory = clickedFile;
					Position pos = new Position(mlvContent
							.getFirstVisiblePosition(), currentDirectory);
					pos.dump();
					sllPos.addFirst(pos);
					mpstCur = null;
					if (clickedFile.isDirectory()) {
						LenovoActivity.this.browseTo(clickedFile);
					}
				} else {
					ViewHolder cache = (ViewHolder) view.getTag();
					if (TAG_FLAG) {
					}
					cache.checkbox.setChecked(!cache.checkbox.isChecked());
				}
			}
		});

		registerForContextMenu(mlvContent);
	}

	private void downloadSelect() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> downloadSelect");
		}
		setContentView(R.layout.lenovo_download_select);
		setTitle(R.string.lenovo);
		downFlag = true;
		btnSelectAll = (Button) findViewById(R.id.btnselectall);
		btnCancleAll = (Button) findViewById(R.id.btncancleall);
		btnCancleAll.setEnabled(false);
		downloadBtn = (TextView) findViewById(R.id.downloadBtn);
		downloadBtn.setVisibility(View.VISIBLE);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_ROCKET_MENU_NOTIFY);
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		downloadBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (null != MarkedFile && 0 != MarkedFile.size()) {
					netFileIds = null;
					netFileNames = null;
					netFileIds = new String[MarkedFile.size()];
					netFileNames = new String[MarkedFile.size()];
					netFileTypes = new boolean[MarkedFile.size()];
					for (int i = 0; i < MarkedFile.size(); i++) {
						netFileIds[i] = MarkedFile.get(i).getID();
						netFileNames[i] = MarkedFile.get(i).getName();
						netFileTypes[i] = MarkedFile.get(i).isDirectory();
						if (TAG_FLAG) {
							Log.d(TAG,
									"the selected download netFileIds is *********"
											+ netFileIds[i]);
							Log.d(TAG,
									"the selected download netFileNames is *********"
											+ netFileNames[i]);
							Log.d(TAG,
									"the selected download netFileTypes is *********"
											+ netFileTypes[i]);
						}
					}
				}
				downLoad(projectState, netFileIds, netFileNames, netFileTypes);
			}
		});
		btnSelectAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				markAllFile();
				// add by PH 091024
				btnCancleAll.setEnabled(true);
				btnSelectAll.setEnabled(false);
				// end PH 091024
			}
		});
		btnCancleAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// check all files in current directory
				unmarkallFile();
				// add by PH 091024
				btnCancleAll.setEnabled(false);
				btnSelectAll.setEnabled(true);
				// add by PH 091024
			}
		});
		mlvContent = (ListView) findViewById(android.R.id.list);
		mlvContent.setAdapter(itemList);
	}

	private void deleteSelect() {
		// TODO Auto-generated method stub
		setContentView(R.layout.lenovo_delete_select);
		setTitle(R.string.lenovo);
		downFlag = false;
		btnSelectAll = (Button) findViewById(R.id.btnselectall);
		btnCancleAll = (Button) findViewById(R.id.btncancleall);
		btnCancleAll.setEnabled(false);
		btnSelectAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				markAllFile();
				btnCancleAll.setEnabled(true);
				btnSelectAll.setEnabled(false);
			}
		});
		btnCancleAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				unmarkallFile();
				btnCancleAll.setEnabled(false);
				btnSelectAll.setEnabled(true);
			}
		});
		mlvContent = (ListView) findViewById(android.R.id.list);
		mlvContent.setAdapter(itemList);
	}

	/**
	 * This function browses to the root-directory of the file-system.
	 */
	private void browseToRoot() {
		Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%browseRoot");

		if (null != NetDiskConstant.NET_DISK_ROOT) {
			browseTo(NetDiskConstant.NET_DISK_ROOT);
		} else {
			Toast.makeText(this, "can not get net disk root",
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * This function browses up one level according to the field:
	 * currentDirectory
	 */
	private void upOneLevel() {

		if ("/".equals(currentDirectory.getAbsolutePath())) {
			Intent intent = new Intent();
			intent.setClass(LenovoActivity.this, TdActivity.class);
			intent.putExtra("projectState", projectState);
			startActivity(intent);
			if (null != mndManager) {
				mndManager.unbindOpService();
				mndManager = null;
			}
			finish();
		} else {
			String parent = this.currentDirectory.getParent();
			if (TAG_FLAG) {
				Log.d(TAG, " upOneLevel the parent is " + parent);
				Log.d(TAG, " upOneLevel the sdroot is " + sdroot);
			}
			if (parent != null) {
				if (parent.equals(root)) {
					parent = sdroot;
				}
				mpstCur = sllPos.poll();
				if (TAG_FLAG) {
					Log.d(TAG,
							" upOneLevel the mpstCur.getDir() is "
									+ mpstCur.getDir());
				}
				this.browseTo(mpstCur.getDir());
			}
		}
	}

	private class MyBrowseToThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public MyBrowseToThread(Context context) {
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			mStop = true;
		}

		private void onBrowseToResult() {
			Message msg = mEH.obtainMessage(BROWSETO_RESULT_MSG, 0, 0, null);
			mEH.sendMessage(msg);
		}

		// add by xieqm 110324
		private void onDeleteNetFile(NetFile netFile) {
			Message msg = mEH.obtainMessage(DELETE_FILE_MSG, 0, 0, netFile);
			mEH.sendMessage(msg);
		}

		private void onCreateNetDir(NetFile netFile) {
			Message msg = mEH.obtainMessage(CREATE_DIR_MSG, 0, 0, netFile);
			mEH.sendMessage(msg);
		}

		private void onRemameNetDir(NetFile netFile) {
			Message msg = mEH.obtainMessage(RENAME_MSG, 0, 0, netFile);
			mEH.sendMessage(msg);
		}

		private void onGetSpace() {
			Message msg = mEH.obtainMessage(SPACE_MSG, 0, 0, null);
			mEH.sendMessage(msg);
		}
		// end
	}

	// private void browseTo(final String path) {
	private void browseTo(final NetFile nf) {
		Log.i(TAG, "==> browseTo");
		if (this.displayMode == DISPLAYMODE.RELATIVE) {

			// show waiting dialog
			ProgressMessageDialog.showMessageDialog(this,
					getString(R.string.lenovo_loading),
					getString(R.string.loading));

			currentDirectory = nf;
			uploadFileId = currentDirectory.getID();
			if (TAG_FLAG)
				Log.d(TAG, "the uploadFileId is =============== "
						+ uploadFileId);
			// final String path = "/";
			// send message to get dir content
			mBrowseToThread = new MyBrowseToThread(this) {
				public void run() {
					if (TAG_FLAG)
						Log.d(TAG,
								"******************** not equal file list ***********"
										+ mndManager.isConnected());
					// String path = "/";

					long id = -1;

					while (true) {
						if (mndManager.isConnected()) {
							id = mndManager.getDirContent(nf);
							break;
						} else {
							try {
								Thread.sleep(200);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}

					Log.d(TAG, "id gotten is " + id);

					NetDiskOpResult result = null;

					do {

						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						result = mndManager.getResult(id);

						if (null != result)
							break;
					} while (true);
					try {
						mlndItems = result.GetOnJSonItemListAll();
					} catch (JSONException e) {
						e.printStackTrace();
					}

					if (TAG_FLAG) {
						Log.e(TAG, "the result is : " + result);
					}

					sortedFileList(mlndItems);

					mBrowseToThread.onBrowseToResult();

				}
			};
			mBrowseToThread.start();

			// If file is a directory,call fill() and browse it.
			if (nf.isDirectory()) {

				setLocationText(nf.getAbsolutePath());
			}
		}
	}

	private void setLocationText(String lt) {
		String relativePath = "";
		String[] strArr;
		String ln = "";
		String result = "";
		lt = Constant.textConvert(this, lt);
		relativePath = lt.replaceFirst(Constant.sdroot,
				getString(R.string.lenovo));
		relativePath = relativePath.trim();
		strArr = TextUtils.split(relativePath, "/");
		for (int i = 1; i < strArr.length; i++) {
			ln += ">" + strArr[i];
		}
		result = getString(R.string.lenovo) + ln;
		// int index = result.lastIndexOf(">");
		// if (result.length() > 30) {
		// result = "......" + result.substring(index, result.length());
		// Log.d(TAG, "the result is ---------------" + result);
		tv.setText(result);
		// } else {
		// if (result.equals(getString(R.string.lenovo))) {
		// tv.setText(result + ">");
		// } else {
		// tv.setText(result);
		// }
		// }
	}

	// add by PH 091011
	private void initMimeTypes() {
		if (mMimeTypes == null) {
			MimeTypeParser mtp = new MimeTypeParser();

			// XmlResourceParser in = getResources().getXml(
			// com.android.internal.R.xml.mimetypes);
			XmlResourceParser in = getResources().getXml(R.xml.mimetypes);
			try {
				mMimeTypes = mtp.fromXmlResource(in);
			} catch (XmlPullParserException e) {
				if (TAG_FLAG)
					Log.e(TAG,
							"************************** XmlPullParserException",
							e);
				throw new RuntimeException(
						"*************************** XmlPullParserException");
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.e(TAG, "************************** IOException", e);
				throw new RuntimeException(
						"************************** IOException", e);
			}
		}
	}

	// end PH 091011

	// add by PH 091016
	HashMap<String, Drawable> mMimeIconMap;

	private Drawable getDrawableForMimetype(String mimetype) {
		Drawable icon = null;
		if (mMimeIconMap == null) {
			mMimeIconMap = new HashMap<String, Drawable>();
		}

		icon = mMimeIconMap.get(mimetype);
		if (icon == null) {
			PackageManager pm = getPackageManager();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			// intent.setType(mimetype);
			intent.setDataAndType(Uri.fromParts("file", "", null), mimetype);

			List<ResolveInfo> lri = pm.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			List<ResolveInfo> lriRe = pm.queryBroadcastReceivers(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			if (lri != null && lri.size() > 0) {
				icon = lri.get(0).loadIcon(pm);
			} else if (lriRe != null && lriRe.size() > 0) {
				icon = lriRe.get(0).loadIcon(pm);
			}

			if (icon != null) {
				mMimeIconMap.put(mimetype, icon);
			} else if (mimetype.equals(ZIP_MIMETYPE)) { // add 2010-12-13 by xqm
				icon = getResources().getDrawable(R.drawable.zip);
				mMimeIconMap.put(mimetype, icon);
			} else {
				icon = getResources().getDrawable(R.drawable.icon_unknown_file);
				mMimeIconMap.put(mimetype, icon);
			}
		}

		return icon;
	}

	private void addAllElements(List<NetFileItem> addTo,
			List<NetFileItem> addFrom) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%addAllElements");
		for (int i = 0; i < addFrom.size(); i++) {
			addTo.add(addFrom.get(i));
		}
	}

	public static HzToPy mHz2Py = null;

	Comparator<NetFileItem> mSortWay = new Comparator<NetFileItem>() {
		public int compare(NetFileItem n1, NetFileItem n2) {
			int ret = 1;
			try {
				if (mHz2Py == null) {
					mHz2Py = new HzToPy(LenovoActivity.this);
				}

				int i = 0;
				String sChar1 = null, sChar2 = null;
				while (true) {
					// if(browsetoThreadFlag && mBrowseToThread.mStop)
					// break;
					String sPy1 = n1.getCharPy(i);
					String sPy2 = n2.getCharPy(i);

					if (sPy1 == null && sPy2 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						if (sChar2.equalsIgnoreCase(sChar1)) {
							String sPy = mHz2Py.Char2Py(sChar1.charAt(0));
							n1.appendPy(sPy);
							n2.appendPy(sPy);
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else if (sPy1 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						sChar2 = n2.getText().substring(i, i + 1);
						if (sChar2.equalsIgnoreCase(sChar1)) {
							n1.appendPy(n2.getCharPy(i));
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							continue;
						}
					} else if (sPy2 == null) {
						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						sChar1 = n1.getText().substring(i, i + 1);
						if (sChar1.equalsIgnoreCase(sChar2)) {
							n2.appendPy(n1.getCharPy(i));
							continue;
						} else {
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else {
						int nRet = sPy1.compareTo(sPy2);
						if (nRet == 0) {
							i += 1;
							continue;
						}

						return nRet;
					}
				}
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.i(TAG,
							"**************catch a IOException in mHz2Py***************");
			}
			return ret;
		}
	};

	private void addIconifiedTextToList(NetFileItem item, List<NetFileItem> list) {
		int nIndex1 = 0;
		int nIndex2 = list.size() - 1;
		int nIndex = 0;

		if (nIndex2 < 0) {
			list.add(item);
			return;
		}

		while (true) {
			nIndex = (nIndex2 + nIndex1) / 2;
			NetFileItem temp = list.get(nIndex);

			int result = mSortWay.compare(item, temp);
			if (result > 0) {
				nIndex1 = nIndex + 1;
			} else if (result < 0) {
				nIndex2 = nIndex - 1;
			} else {
				list.add(nIndex, item);
				break;
			}

			if (nIndex1 > nIndex2) {
				if (result > 0) {
					if (nIndex >= list.size() - 1) {
						list.add(item);
					} else {
						list.add(nIndex + 1, item);
					}
				} else {
					list.add(nIndex, item);
				}

				break;
			}
		}
	}

	private void sortedFileList(List<NetFile> items) {

		if (items == null) {
			return;
		}

		Drawable currentUsrIcon = getResources().getDrawable(
				R.drawable.icon_default_folder);
		Drawable fileIcon = null;

		this.mListDir.clear();
		this.mListFile.clear();
		this.directoryEntries.clear();

		for (NetFile currentFile : items) {
			if (browsetoThreadFlag && mBrowseToThread.mStop)
				break;

			if (TAG_FLAG)
				Log.i(TAG,
						"currentFile.isDirectory()============================"
								+ currentFile.isDirectory());
			if (currentFile.isDirectory()) {
				if (newDirFlag) {
					NetFileItem newtFileItem = new NetFileItem(currentUsrIcon,
							currentFile, false);
					mListDir.add(newtFileItem);
				} else {
					addIconifiedTextToList(new NetFileItem(currentUsrIcon,
							currentFile, false), mListDir);
				}
			} else {
				String fileName = currentFile.getName();
				String mimetype = mMimeTypes
						.getMimeType(fileName.toLowerCase());
				if (mimetype == null) {
					if (FileUtil.getExtension(fileName).equals(".p12")) {
						fileIcon = getResources().getDrawable(
								R.drawable.ic_menu_login);
					} else {
						fileIcon = getResources().getDrawable(
								R.drawable.icon_unknown_file);
					}
				} else {
					fileIcon = getDrawableForMimetype(mimetype);
				}

				switch (this.displayMode) {
				case ABSOLUTE:
				case RELATIVE:
					addIconifiedTextToList(new NetFileItem(fileIcon,
							currentFile, false), mListFile);
					break;
				}
			}
		}

		addAllElements(directoryEntries, mListDir);
		addAllElements(directoryEntries, mListFile);
	}

	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo) {
		if (State == _SELECT)
			return;
		else if (State == _LIST) {
			super.onCreateContextMenu(menu, view, menuInfo);
			AdapterView.AdapterContextMenuInfo info;
			try {
				info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			} catch (ClassCastException e) {
				if (TAG_FLAG)
					Log.e(TAG, "***********bad menuInfo************", e);
				return;
			}
			menu.add(0, DOWNLOAD, 0, R.string.download);
			menu.add(0, RENAME_ID, 0, R.string.menu_rename);
			menu.add(0, DEL_ID, 0, R.string.menu_delete);
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		delete = false;
		download = false;
		this.itemList.notifyDataSetChanged();
		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;
		}
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		final NetFileItem ob = (NetFileItem) mlvContent.getAdapter().getItem(
				info.position);
		if (ob == null || ob.getFile() == null)
			return false;
		MarkedFile.add(ob.getFile());
		switch (item.getItemId()) {
		case DOWNLOAD:
			netFileIds = null;
			netFileNames = null;
			netFileIds = new String[1];
			netFileNames = new String[1];
			netFileTypes = new boolean[1];
			netFileIds[0] = ob.getFile().getID();
			netFileNames[0] = ob.getFile().getName();
			netFileTypes[0] = ob.getFile().isDirectory();
			downLoad(projectState, netFileIds, netFileNames, netFileTypes);
			break;
		case DEL_ID:
			// if (TAG_FLAG) {
			// Log.d(TAG, "the select file is " + netFileNames[0]);
			// }
			MarkedFile.clear();
			MarkedFile.add(ob.getFile());
			delFile(MarkedFile);
			State = _LIST;
			initState();
			break;
		case RENAME_ID:
			rename(ob.getFile());
			break;
		default:
			return super.onContextItemSelected(item);
		}
		return true;

	}

	private void preDelete() {
		menuFlags = DEL_ID + "";
		if (delete) {
			if (!MarkedFile.isEmpty()) {
				MarkedFile.clear();
				isSelected = false;
			}
			delete = false;
		}
		State = _SELECT;
		initState();
		setLocationText(currentDirectory.getAbsolutePath());
	}

	private void renameToNewName(final NetFile netFile, final String newName) {
		if (TAG_FLAG) {
			Log.e(TAG, "==> renameToNewName");
		}
		if (null == netFile || null == newName || 0 == newName.trim().length()) {
			Log.e(TAG, "invalid parameter in renameToNewName");
			return;
		}

		if (!FileUtil.isNameUseable(newName, netFile.isDirectory())) {
			ProgressMessageDialog.cancelDialog();
			ErrorMessageDialog.showMessageDialog(LenovoActivity.this,
					getString(R.string.namebad));
			return;
		}

		mOperatorThread = new MyBrowseToThread(LenovoActivity.this) {
			long id = -1;

			public void run() {

				while (!mndManager.isConnected()) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				NetDiskOpResult result = null;

				id = mndManager.renameDirorFile(netFile, newName);

				do {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					result = mndManager.getResult(id);
				} while (null == result);

				try {
					renameNetFile = result.getRenameItemResult();
					if (renameNetFile != null) {
						mlndItems.remove(netFile);
						mlndItems.add(renameNetFile);
						newDirFlag = true;
						mOperatorThread.onRemameNetDir(netFile);
					} else {
						mOperatorThread.interrupt();
						ProgressMessageDialog.cancelDialog();
						mEH.post(new Runnable() {

							@Override
							public void run() {
								String errorMsg = NetDiskOpResult
										.strGetErrorMsg();
								if (TAG_FLAG) {
									Log.d(TAG,
											"the errorMsg is ================ "
													+ errorMsg);
									ErrorMessageDialog.showMessageDialog(
											LenovoActivity.this, errorMsg);
								}
							}
						});
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		};
		mOperatorThread.start();
	}

	private void rename(final NetFile netFile) {
		LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(
				R.layout.dlg_content_newname, null);
		TextView tv = (TextView) layout.findViewById(R.id.filename_view);
		tv.setText(R.string.dlg_rename_msg_input);
		final EditText filename_edit = (EditText) layout
				.findViewById(R.id.filename_edit);
		filename_edit.setText(netFile.getName());
		filename_edit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
						FileUtil.FILE_NAME_NUM_MAX) });
		if (netFile.isFile()) {
			filename_edit.setSelection(0,
					FileUtil.getFileNameWithoutExt(netFile.getName()).length());
		} else {
			filename_edit.setSelectAllOnFocus(true);
		}
		renameDialog = new AlertDialog.Builder(LenovoActivity.this)
				.setTitle(R.string.menu_rename)
				.setView(layout)
				.setPositiveButton(R.string.dlg_btn_ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								ProgressMessageDialog.showMessageDialog(
										LenovoActivity.this,
										getString(R.string.menu_rename),
										getString(R.string.rename_loading));
								newName = filename_edit.getText().toString();
								if (TAG_FLAG) {
									Log.d(TAG, "the new name is " + newName);
								}
								renameToNewName(netFile, newName);
							}
						})
				.setNegativeButton(R.string.dlg_btn_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}

						}).show();
	}

	private void downLoad(final String projectState, String[] netFileIds,
			String[] netFileNames, boolean[] netFileTypes) {
		mDownload = DirDefines.DOWNLOAD;
		
		if (null != MarkedFile && 0 != MarkedFile.size()) {
			netFileIds = null;
			netFileNames = null;
			netFileIds = new String[MarkedFile.size()];
			netFileNames = new String[MarkedFile.size()];
			netFileTypes = new boolean[MarkedFile.size()];
			for (int i = 0; i < MarkedFile.size(); i++) {
				netFileIds[i] = MarkedFile.get(i).getID();
				netFileNames[i] = MarkedFile.get(i).getName();
				netFileTypes[i] = MarkedFile.get(i).isDirectory();
				
			}
		}
		
		if (projectState.equals(DirDefines.mDir1)) {
			Intent intent = new Intent();
			intent.putExtra("projectState", projectState);
			intent.putExtra("mDownload", mDownload);
			intent.putExtra("netFileIds", netFileIds);
			intent.putExtra("netFileNames", netFileNames);
			intent.putExtra("netFileTypes", netFileTypes);
			intent.setClass(LenovoActivity.this, TdActivity.class);
			startActivity(intent);
		} else if (projectState.equals(DirDefines.mDir3)) {
			if (mDownload.equals(DirDefines.DOWNLOAD)) {
				Intent intent = new Intent();
				intent.setAction(OPEN_SAVE);
				intent.putExtra("projectState", DirDefines.mDir3);
				intent.putExtra("mDownload", mDownload);
				intent.putExtra("netFileIds", netFileIds);
				intent.putExtra("netFileNames", netFileNames);
				intent.putExtra("netFileTypes", netFileTypes);
				intent.putExtra("request_code", MODE_SELECT_PATH);
				startActivityForResult(intent, MODE_SELECT_PATH);
			}
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// return super.onCreateOptionsMenu(menu);
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onCreateOptionsMenu");
		boolean result = super.onCreateOptionsMenu(menu);
		inputMethodManager.hideSoftInputFromWindow(mlvContent.getWindowToken(),
				0);
		isSelected = false;
		menu.add(0, PRE_UPLOAD, 0, R.string.upload);
		menu.add(0, PRE_DOWNLOAD, 0, R.string.download);
		// menu item for SELECT state, group id is 1
		menu.add(0, DEL_ID, 0, R.string.menu_delete).setIcon(
				R.drawable.ic_menu_delete);
		menu.add(0, SWITCHING_DIRECTORY, 0, R.string.switching_directory)
				.setIcon(R.drawable.switch_directory);
		// menu item for LIST state, group id is 0
		menu.add(0, NEW_ID, 0, R.string.menu_new_folder);
		menu.add(0, TASK_MANAGER, 0, R.string.task_manager);
		menu.add(1, DELETE, 0, R.string.menu_delete).setIcon(
				R.drawable.ic_menu_delete);
		return result;
	}

	public boolean onPrepareOptionsMenu(Menu menu) {
		// super.onPrepareOptionsMenu(menu);
		mUpload = null;
		mDownload = null;
		inputMethodManager.hideSoftInputFromWindow(mlvContent.getWindowToken(),
				0);
		switch (State) {
		case _LIST:
			if (!sdRemoved) {
				// visible items of LIST state
				menu.setGroupVisible(0, true);
				// invisible items of SELECT state
				menu.setGroupVisible(1, false);
				// make "paste" invisible, only if Cut or Copy action is coming
				if (0 != mlndItems.size()) {
					menu.findItem(PRE_DOWNLOAD).setEnabled(true);
				} else {
					menu.findItem(PRE_DOWNLOAD).setEnabled(false);
				}

				nothing = false;
				if (nothing) {
					menu.findItem(DEL_ID).setVisible(false);
				} else {
					menu.findItem(DEL_ID).setVisible(true);
					if (0 != mlndItems.size()) {
						menu.findItem(DEL_ID).setEnabled(true);
					} else {
						menu.findItem(DEL_ID).setEnabled(false);
					}
				}
			} else {
				menu.setGroupVisible(0, false);
				// invisible items of SELECT state
				menu.setGroupVisible(1, false);
			}
			break;
		case _SELECT:
			menu.setGroupVisible(0, false);
			menu.setGroupVisible(1, false);
			if (menuFlags.equals(DEL_ID + "")) {
				menu.setGroupVisible(1, true);
				if (!isSelected || nothing) {
					menu.setGroupEnabled(1, false);
				} else {
					menu.setGroupEnabled(1, true);
				}
			}
			break;
		}
		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onOptionsItemSelected");
		mUpload = null;
		mDownload = null;
		switch (item.getItemId()) {
		case PRE_UPLOAD:
			if (TAG_FLAG)
				Log.d(TAG, "=================PRE_UPLOAD==========");
			preUpload(projectState);
			break;
		case PRE_DOWNLOAD:
			preDownload();
			break;
		case DEL_ID:
			preDelete();
			break;
		case DELETE:
			if (MarkedFile.isEmpty()) {
				Toast.makeText(this, R.string.nosource, 3).show();
				break;
			}
			for (int i = 0; i < MarkedFile.size(); i++) {
				if (TAG_FLAG)
					Log.d(TAG, "MarkedFile========"
							+ MarkedFile.get(i).getName());
			}
			delFile(MarkedFile);
			State = _LIST;
			initState();
			break;
		case SWITCHING_DIRECTORY:
			switchingDirectory();
			break;
		case NEW_ID:
			LayoutInflater factory = LayoutInflater.from(LenovoActivity.this);
			final View textEntryView = factory.inflate(
					R.layout.alert_dialog_text_entry, null);
			final TextView textView = (TextView) textEntryView
					.findViewById(R.id.filename_view);
			textView.setText(R.string.new_directoryname);
			final EditText eText = (EditText) textEntryView
					.findViewById(R.id.filename_edit);
			eText.setText(getResources().getString(R.string.default_dir_name));
			eText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
					FILE_NAME_NUM_MAX) });
			eText.selectAll();
			new AlertDialog.Builder(LenovoActivity.this)
					.setTitle(R.string.inputname)
					.setView(textEntryView)
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String name = eText.getText().toString()
											.trim();
									if (TAG_FLAG)
										Log.i(TAG, "********name = " + name
												+ "**********");
									if (name.length() > 0
											&& name.length() <= FILE_NAME_NUM_MAX) {
										if (isNameUseable(name, true) == false) {
											Toast.makeText(LenovoActivity.this,
													R.string.namebad,
													Toast.LENGTH_SHORT).show();
										} else {

											//
											// NetFile netFile = new NetFile(
											// "1300933610116208337",
											// name, "/", null);
											if (TAG_FLAG) {
												if (TAG_FLAG)
													Log.i(TAG,
															"the new netFile is "
																	+ name);
											}
											createDir(currentDirectory, name);
											State = _LIST;
											initState();
										}
									} else if (name.length() > FILE_NAME_NUM_MAX) {
										Toast.makeText(LenovoActivity.this,
												R.string.name_too_long,
												Toast.LENGTH_SHORT).show();
									} else {
										Toast.makeText(LenovoActivity.this,
												R.string.nameempty,
												Toast.LENGTH_SHORT).show();
									}
								}
							})
					.setNegativeButton(R.string.alert_dialog_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
			break;
		case TASK_MANAGER:
//			Intent intent = new Intent();
//			intent.putExtra("download", DirDefines.DOWNLOAD);
//			intent.putExtra("upload", DirDefines.UPLOAD);
//			intent.setClass(LenovoActivity.this, TaskManagerActivity.class);
//			startActivity(intent);
			Intent loadintent = new Intent(LenovoActivity.this, TaskManagerActivity.class);
			startActivity(loadintent);
			break;
		default:
			if (TAG_FLAG)
				Log.i(TAG, "*************unknowed ID**************");
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void preUpload(String projectState) {
		if (projectState.equals(DirDefines.mDir1)) {
			mUpload = DirDefines.UPLOAD;
			Intent intent = new Intent();
			intent.putExtra("projectState", projectState);
			intent.putExtra("mUpload", mUpload);
			intent.putExtra("uploadFileId", uploadFileId);
			intent.setClass(LenovoActivity.this, TdActivity.class);
			startActivity(intent);
		} else if (projectState.equals(DirDefines.mDir3)) {
			Intent intent = new Intent();
			intent.setAction(OPEN_SAVE);
			intent.putExtra("uploadFileId", uploadFileId);
			intent.putExtra("request_code", LENOVO_MODE_SAVE_FILE);
			intent.putExtra("FILE_FILTER",
					".jpg .doc .txt .ppt .xls .rmvb .mp3 .flv .apk .png .vcf");
			startActivityForResult(intent, LENOVO_MODE_SAVE_FILE);
		}
	}

	private void preDownload() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> preDownload");
			Log.d(TAG, "the download is **********" + download);
		}
		mDownload = DirDefines.DOWNLOAD;
		menuFlags = PRE_DOWNLOAD + "";
		if (download) {
			if (!MarkedFile.isEmpty()) {
				MarkedFile.clear();
				isSelected = false;
			}
			download = false;
		}
		State = _SELECT;
		initState();
		setLocationText(currentDirectory.getAbsolutePath());
	}

	private void switchingDirectory() {
		IntentFilter commandFilters = new IntentFilter();
		commandFilters.addAction(Intent.ACTION_MEDIA_MOUNTED);
		commandFilters.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		commandFilters.addAction(Intent.ACTION_MEDIA_REMOVED);
		commandFilters.addAction(Intent.ACTION_MEDIA_SHARED);
		commandFilters.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
		commandFilters.addAction(Intent.ACTION_MEDIA_CHECKING);
		commandFilters.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		commandFilters.addAction(Intent.ACTION_MEDIA_NOFS);
		commandFilters.addDataScheme("file");
		registerReceiver(sdCardIntentReceiver, commandFilters);
		mReceiver = true;

		layout = (LinearLayout) getLayoutInflater().inflate(
				R.layout.dir_dialog_list, null);
		sdcardText = (TextView) layout.findViewById(R.id.sdcardText);
		phoneLayout = (LinearLayout) layout.findViewById(R.id.phoneLayout);
		sdcardLayout = (LinearLayout) layout.findViewById(R.id.sdcardLayout);
		lenovoLayout = (LinearLayout) layout.findViewById(R.id.lenovoLayout);
		phoneLayout.setOnTouchListener(this);
		sdcardLayout.setOnTouchListener(this);
		lenovoLayout.setOnTouchListener(this);
		phoneLayout.setOnClickListener(LenovoActivity.this);
		lenovoLayout.setOnClickListener(LenovoActivity.this);
		if (mUpload != null || mDownload != null) {
			lenovoLayout.setVisibility(View.GONE);
		} else {
			lenovoLayout.setVisibility(View.VISIBLE);
		}
		if (sdCardtatus.equals(Environment.MEDIA_SHARED)
				|| sdCardtatus.equals(Environment.MEDIA_UNMOUNTED)
				|| sdCardtatus.equals(Environment.MEDIA_CHECKING)) {
			if (projectState.equals(DirDefines.mDir1)) {
				sdcardText.setTextColor(android.graphics.Color.GRAY);
				sdcardLayout.setEnabled(false);
			} else if (projectState.equals(DirDefines.mDir3)) {
				sdcardLayout.setVisibility(View.GONE);
			}
		} else {
			if (projectState.equals(DirDefines.mDir1)) {
				sdcardText.setTextColor(android.graphics.Color.WHITE);
				sdcardLayout.setEnabled(true);
				sdcardLayout.setOnClickListener(this);
			} else if (projectState.equals(DirDefines.mDir3)) {
				sdcardLayout.setVisibility(View.GONE);
			}
		}
		dialog = new AlertDialog.Builder(LenovoActivity.this)
				.setTitle(R.string.switching_directory)
				.setView(layout)
				.setPositiveButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
							}
						}).show();
	}

	private void loginLenovo() {
		dialog.cancel();
		State = _LIST;
		initState();
		browseToRoot();
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if (TAG_FLAG) {
			Log.d(TAG, "projectState=================" + projectState);
			Log.d(TAG, "mUpload=================" + mUpload);
			Log.d(TAG, "mDownload=================" + mDownload);
		}
		Intent intent = new Intent();
		if (DirDefines.mDir1.equals(projectState)) {
			switch (view.getId()) {
			case R.id.phoneLayout:
				intent.putExtra("projectState", projectState);
				intent.setClass(LenovoActivity.this,
						com.lenovo.leos.filebrowser.ui.FileBrowser.class);
				startActivity(intent);
//				if (null != mndManager) {
//					mndManager.unbindOpService();
					mndManager = null;
//				}
				finish();
				break;
			case R.id.sdcardLayout:
				intent.putExtra("projectState", projectState);
				intent.setClass(LenovoActivity.this,
						com.lenovo.leos.filebrowser.ui.FileBrowser.class);
				startActivity(intent);
//				if (null != mndManager) {
//					mndManager.unbindOpService();
					mndManager = null;
//				}
				finish();
				break;
			case R.id.lenovoLayout:
				dialog.cancel();
				loginLenovo();
				break;
			}
		} else if (DirDefines.mDir3.equals(projectState)) {
			switch (view.getId()) {
			case R.id.phoneLayout:
				intent.putExtra("projectState", projectState);
				intent.setClass(LenovoActivity.this,
						com.lenovo.leos.filebrowser.ui.FileBrowser.class);
				startActivity(intent);
//				if (null != mndManager) {
//					mndManager.unbindOpService();
					mndManager = null;
//				}
				finish();
				break;
			case R.id.lenovoLayout:
				dialog.cancel();
				loginLenovo();
				break;

			}
		}
	}

	private BroadcastReceiver sdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (TAG_FLAG)
				Log.d(TAG, "#################### SDaction = " + action);
			if (DirDefines.mDir1.equals(projectState)) {
				if (action.equals(Intent.ACTION_MEDIA_SHARED)
						|| action.equals(Intent.ACTION_MEDIA_UNMOUNTABLE)
						|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
						|| action.equals(Intent.ACTION_MEDIA_BAD_REMOVAL)
						|| action.equals(Intent.ACTION_MEDIA_NOFS)
						|| action.equals(Intent.ACTION_MEDIA_CHECKING)
						|| action.equals(Intent.ACTION_MEDIA_REMOVED)) {
					sdcardText.setEnabled(false);
					sdcardText.setTextColor(android.graphics.Color.GRAY);
				} else {
					sdcardText.setEnabled(true);
					sdcardText.setTextColor(android.graphics.Color.WHITE);
					sdcardLayout.setOnClickListener(LenovoActivity.this);
				}
			}
		}
	};

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			phoneLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			sdcardLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			lenovoLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
			lenovoLayout.setBackgroundColor(0);
		} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
			lenovoLayout.setBackgroundColor(0);
		}
		return false;
	}

	private void unmarkallFile() {
		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;

			itemList.notifyDataSetChanged();
		}
	}

	/*
	 * make all files in the current directory checked
	 */
	private void markAllFile() {
		MarkedFile.clear();
		for (int i = 0; i < directoryEntries.size(); i++) {
			if (!directoryEntries.get(i).getFile().isHidden()) {
				MarkedFile.add(directoryEntries.get(i).getFile());
			}
		}
		if (TAG_FLAG) {
			Log.d(TAG, "the MarkedFile size is  " + MarkedFile.size());
		}
		isSelected = true;
		itemList.notifyDataSetChanged();
	}

	public void delFile(final List<NetFile> list) {
		if (TAG_FLAG) {
			Log.d(TAG, " ==> delFile  " + list.size());
		}
		count = 0;
		new AlertDialog.Builder(LenovoActivity.this)
				.setTitle(R.string.delete_file)
				.setMessage(R.string.lenovo_delete)
				.setPositiveButton(R.string.alert_dialog_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

								ProgressMessageDialog.showMessageDialog(
										LenovoActivity.this,
										getString(R.string.delete_file),
										getString(R.string.delete_loading));
								mOperatorThread = new MyBrowseToThread(
										LenovoActivity.this) {
									long id = -1;

									public void run() {

										while (!mndManager.isConnected()) {
											try {
												Thread.sleep(1000);
											} catch (InterruptedException e) {
												e.printStackTrace();
											}
										}
										NetDiskOpResult result = null;
										for (int i = 0; i < list.size(); i++) {
											id = mndManager
													.deleteFileorDir(list
															.get(i));
											do {
												try {
													Thread.sleep(100);
												} catch (InterruptedException e) {
													e.printStackTrace();
												}
												result = mndManager
														.getResult(id);
											} while (null == result);

											mOperatorThread
													.onDeleteNetFile(list
															.get(i));
											try {
												delFlag = result
														.GetDelDirStutes();
												if (delFlag) {
													mNetFile = list.get(i);
													mlndItems.remove(mNetFile);
													count++;
												} else {
													mOperatorThread.interrupt();
													ProgressMessageDialog
															.cancelDialog();

													mEH.post(new Runnable() {

														@Override
														public void run() {
															String errorMsg = NetDiskOpResult
																	.strGetErrorMsg();
															if (TAG_FLAG) {
																Log.d(TAG,
																		"the errorMsg is ================ "
																				+ errorMsg);
																ErrorMessageDialog
																		.showMessageDialog(
																				LenovoActivity.this,
																				errorMsg);
															}
														}
													});
												}
												if (TAG_FLAG) {
													Log.d(TAG, "the count is  "
															+ count);
												}
											} catch (JSONException e) {
												e.printStackTrace();
											}
										}
									}
								};
								mOperatorThread.start();
							}

						})
				.setNeutralButton(R.string.alert_dialog_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	/*
	 * create dir
	 */
	private void createDir(final NetFile netFile, final String name) {
		if (TAG_FLAG) {
			Log.d(TAG, "== > creatDir" + netFile.getName());
		}
		ProgressMessageDialog.showMessageDialog(LenovoActivity.this,
				getString(R.string.menu_new_folder),
				getString(R.string.loading));

		mOperatorThread = new MyBrowseToThread(LenovoActivity.this) {
			long id = -1;

			public void run() {

				while (!mndManager.isConnected()) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				NetDiskOpResult result = null;
				id = mndManager.createDir(netFile, name);
				do {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					result = mndManager.getResult(id);
				} while (null == result);

				mOperatorThread.onCreateNetDir(netFile);
				NetFile newNetFile = null;
				try {
					newNetFile = result.GetNewDir();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (newNetFile != null) {
					mlndItems.add(newNetFile);
					newDirFlag = true;
				} else {
					mOperatorThread.interrupt();
					ProgressMessageDialog.cancelDialog();
					mEH.post(new Runnable() {

						@Override
						public void run() {
							String errorMsg = NetDiskOpResult.strGetErrorMsg();
							if (TAG_FLAG) {
								Log.d(TAG, "the errorMsg is ================ "
										+ errorMsg);
								ErrorMessageDialog.showMessageDialog(
										LenovoActivity.this, errorMsg);
							}
						}
					});
				}
			}
		};
		mOperatorThread.start();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (!MarkedFile.isEmpty()) {
			MarkedFile.clear();
			isSelected = false;
		}
		isSelected = false;
		delete = false;
		download = false;

		switch (requestCode) {
		default:
			break;
		}
	}

	public void exit() {
		System.exit(0);
	}

	private boolean isNameUseable(String name, boolean isDerectory) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%isNameUseable");
		// /\:?<>"|*.'
		boolean ret = false;
		if (name.length() > 0) {
			if (name.startsWith(".") == false
			/* && name.startsWith(" ") == false */
			&& name.contains("/") == false && name.contains("\\") == false
					&& name.contains(":") == false
					&& name.contains("?") == false
					&& name.contains("？") == false
					&& name.contains("<") == false
					&& name.contains(">") == false
					&& name.contains("\"") == false
					&& name.contains("|") == false
					&& name.contains("*") == false
					// && ((isDerectory==true)?(name.contains(".") ==
					// false):true)
					&& name.contains("'") == false) {
				ret = true;
			}
		}

		return ret;
	}

	public void onTitleIconClick() {
		Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onTitleIconClick");
		if (State == _SELECT) {
			// select2list();
			State = _LIST;
			initState();
		} else if (State == _LIST) {
			upOneLevel();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%onKeyDown");
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK: {
			onTitleIconClick();
			return true;
		}
		}
		return super.onKeyDown(keyCode, event);
	}

}
